var mongoose = require('mongoose')
var ObjectId = mongoose.Schema.Types.ObjectId

var ImageSchema = new mongoose.Schema({
    name: String,
    desc: String,
    size: Number,
    num: Number,
    url: String,
    user: {
        type: ObjectId,
        ref: 'User'
    },
    meta: {
        createAt: {
            type: Date,
            default: Date.now()
        },
        updateAt: {
            type: Date,
            default: Date.now()
        }
    }
})

ImageSchema.pre('save', function(next) {
    if (this.isNew) {
        this.meta.createAt = this.meta.updateAt = Date.now()
    }
    else {
        this.meta.updateAt = Date.now()
    }
})

ImageSchema.statics = {
    fetch: function(cb) {
        return this
            .find({})
            .sort('meta.updateAt')
            .exec(cb)
    },
    findById: function(id, cb) {
        return this
            .findOne({_id: id})
            .exec(cb)
    }
}

module.exports = ImageSchema